/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sdc.utility;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

/**
 *
 * @author hy
 */
public class WeightedLot<E> {
	private Map<E,Double> store = new HashMap<E, Double>();

	private Random r;

	public WeightedLot(Random r){
		this.r=r;
	}

	public WeightedLot(){
		this.r= new Random();
	}

	public void add(E o, double weight){
		this.store.put(o, weight);
	}

	public E pickup(){
		Map<E,Double> tmp = new HashMap<E, Double>();
		double sum = 0.0;
		for(double i : this.store.values()){
			sum+=i;
		}
		for(E o : this.store.keySet()){
			tmp.put(o, this.store.get(o)/sum);
		}
		double cur=0.0;
		double rnd=this.r.nextDouble();
		for(Entry<E,Double> i: tmp.entrySet()){
			double pre=cur;
			cur+=i.getValue();
			if(pre<rnd && cur>=rnd){
				return i.getKey();
			}
		}
		return null;
	}

	public void remove(E o){
		this.store.remove(o);
	}

}
